<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str;

class H5Controller extends Controller
{
    /**
     * H5应用入口页面
     * 用于微信公众号中访问UniApp编译后的H5项目
     */
    public function index(Request $request)
    {
        // 获取微信相关参数
        $code = $request->get('code');
        $state = $request->get('state');
        
        // 生成随机字符串用于微信JS-SDK
        $nonceStr = Str::random(16);
        $timestamp = time();
        
        // 记录访问日志
        \Log::info('H5应用访问', [
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'code' => $code,
            'state' => $state,
            'nonceStr' => $nonceStr,
            'timestamp' => $timestamp
        ]);
        
        // 读取打包后的 H5 index.html（当前放置于 public/h5）
        $h5IndexPath = public_path('h5/index.html');
        if (!file_exists($h5IndexPath)) {
            \Log::error('H5 index.html 文件不存在', ['path' => $h5IndexPath]);
            return response('H5应用未构建，请先在 hhm_h5 执行构建', 404);
        }
        $html = file_get_contents($h5IndexPath);
        
        // 注入微信配置
        $wechatConfig = json_encode([
            'code' => $code,
            'state' => $state,
            'appId' => config('wechat.app_id'),
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr,
            'signature' => '',
            'jsApiList' => [
                'updateAppMessageShareData',
                'updateTimelineShareData',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'getLocation',
                'openLocation',
                'scanQRCode'
            ],
        ], JSON_UNESCAPED_UNICODE);
        $inject = "\n<script>window.wechatConfig = {$wechatConfig};</script>\n";
        $html = str_replace('</head>', $inject . '</head>', $html);
        
        return response($html)->header('Content-Type', 'text/html; charset=utf-8');
    }
    
    /**
     * 微信授权回调处理
     */
    public function wechatCallback(Request $request)
    {
        $code = $request->get('code');
        $state = $request->get('state');
        
        \Log::info('微信授权回调', [
            'code' => $code,
            'state' => $state,
            'timestamp' => now()
        ]);
        
        // 这里可以处理微信授权逻辑
        // 比如获取用户信息、设置session等
        
        // 重定向到H5应用
        return redirect()->route('h5.index');
    }
    
    /**
     * 获取微信JS-SDK配置
     */
    public function getWechatConfig(Request $request)
    {
        try {
            // 这里需要实现微信JS-SDK的签名算法
            // 具体实现需要根据你的微信配置
            
            $url = $request->get('url');
            $timestamp = time();
            $nonceStr = $this->generateNonceStr();
            
            // 这里需要根据你的微信配置生成签名
            $signature = $this->generateSignature($url, $timestamp, $nonceStr);
            
            return response()->json([
                'success' => true,
                'data' => [
                    'appId' => config('wechat.app_id'),
                    'timestamp' => $timestamp,
                    'nonceStr' => $nonceStr,
                    'signature' => $signature,
                    'jsApiList' => [
                        'updateAppMessageShareData',
                        'updateTimelineShareData',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo',
                        'onMenuShareQZone',
                        'getLocation',
                        'chooseLocation'
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            \Log::error('获取微信JS-SDK配置失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '获取微信配置失败'
            ], 500);
        }
    }
    
    /**
     * 生成随机字符串
     */
    private function generateNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    /**
     * 生成微信JS-SDK签名
     * 这里需要根据你的微信配置实现具体的签名算法
     */
    private function generateSignature($url, $timestamp, $nonceStr)
    {
        try {
            // 1. 获取access_token
            $accessToken = $this->getAccessToken();
            
            // 2. 获取jsapi_ticket
            $jsapiTicket = $this->getJsapiTicket($accessToken);
            
            // 3. 生成签名
            $string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
            $signature = sha1($string);
            
            \Log::info('微信JS-SDK签名生成', [
                'url' => $url,
                'timestamp' => $timestamp,
                'nonceStr' => $nonceStr,
                'jsapiTicket' => $jsapiTicket,
                'string' => $string,
                'signature' => $signature
            ]);
            
            return $signature;
        } catch (\Exception $e) {
            \Log::error('生成微信签名失败', [
                'error' => $e->getMessage(),
                'url' => $url,
                'timestamp' => $timestamp,
                'nonceStr' => $nonceStr
            ]);
            
            return '';
        }
    }
    
    /**
     * 获取微信access_token
     */
    private function getAccessToken()
    {
        $cacheKey = 'wechat_access_token';
        $accessToken = \Cache::get($cacheKey);
        
        if (!$accessToken) {
            $appId = config('wechat.app_id');
            $appSecret = config('wechat.app_secret');
            
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
            
            $response = file_get_contents($url);
            $data = json_decode($response, true);
            
            if (isset($data['access_token'])) {
                $accessToken = $data['access_token'];
                \Cache::put($cacheKey, $accessToken, 7000); // 缓存7000秒
                
                \Log::info('获取微信access_token成功', [
                    'access_token' => substr($accessToken, 0, 10) . '...',
                    'expires_in' => $data['expires_in'] ?? 0
                ]);
            } else {
                \Log::error('获取微信access_token失败', [
                    'response' => $response,
                    'app_id' => $appId
                ]);
                throw new \Exception('获取access_token失败: ' . $response);
            }
        }
        
        return $accessToken;
    }
    
    /**
     * 获取微信jsapi_ticket
     */
    private function getJsapiTicket($accessToken)
    {
        $cacheKey = 'wechat_jsapi_ticket';
        $jsapiTicket = \Cache::get($cacheKey);
        
        if (!$jsapiTicket) {
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi";
            
            $response = file_get_contents($url);
            $data = json_decode($response, true);
            
            if (isset($data['ticket'])) {
                $jsapiTicket = $data['ticket'];
                \Cache::put($cacheKey, $jsapiTicket, 7000); // 缓存7000秒
                
                \Log::info('获取微信jsapi_ticket成功', [
                    'ticket' => substr($jsapiTicket, 0, 10) . '...',
                    'expires_in' => $data['expires_in'] ?? 0
                ]);
            } else {
                \Log::error('获取微信jsapi_ticket失败', [
                    'response' => $response,
                    'access_token' => substr($accessToken, 0, 10) . '...'
                ]);
                throw new \Exception('获取jsapi_ticket失败: ' . $response);
            }
        }
        
        return $jsapiTicket;
    }
    
    /**
     * 创建微信菜单
     */
    public function createMenu()
    {
        try {
            $accessToken = $this->getAccessToken();
            $menuData = config('wechat.menu');
            
            $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$accessToken}";
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($menuData));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            
            $response = curl_exec($ch);
            curl_close($ch);
            
            $result = json_decode($response, true);
            
            \Log::info('微信菜单创建', [
                'menu_data' => $menuData,
                'response' => $result
            ]);
            
            if ($result['errcode'] == 0) {
                return response()->json(['success' => true, 'message' => '菜单创建成功']);
            } else {
                return response()->json(['success' => false, 'message' => '菜单创建失败: ' . $result['errmsg']]);
            }
        } catch (\Exception $e) {
            \Log::error('微信菜单创建异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json(['success' => false, 'message' => '菜单创建异常: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除微信菜单
     */
    public function deleteMenu()
    {
        try {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$accessToken}";
            
            $response = file_get_contents($url);
            $result = json_decode($response, true);
            
            \Log::info('微信菜单删除', [
                'response' => $result
            ]);
            
            if ($result['errcode'] == 0) {
                return response()->json(['success' => true, 'message' => '菜单删除成功']);
            } else {
                return response()->json(['success' => false, 'message' => '菜单删除失败: ' . $result['errmsg']]);
            }
        } catch (\Exception $e) {
            \Log::error('微信菜单删除异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json(['success' => false, 'message' => '菜单删除异常: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取微信菜单
     */
    public function getMenu()
    {
        try {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token={$accessToken}";
            
            $response = file_get_contents($url);
            $result = json_decode($response, true);
            
            \Log::info('微信菜单获取', [
                'response' => $result
            ]);
            
            return response()->json(['success' => true, 'data' => $result]);
        } catch (\Exception $e) {
            \Log::error('微信菜单获取异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json(['success' => false, 'message' => '菜单获取异常: ' . $e->getMessage()]);
        }
    }
}
